package org.feichao.imagegenerator;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * 文字素材接口
 * @author zhangzc@djcars.cn
 * @create 2016/8/9
 */
public class TextBean extends Drawable{

    public String text;

    public Font font;

    public int x;

    public int y;

    public int rotateDegree = 0;

    public Color textColor = Color.BLACK;

    public int marginBottom = 10;

    public TextBean(String text, Font font, int x, int y, Color textColor) {
        this.text = text;
        this.font = font;
        this.x = x;
        this.y = y;
        this.textColor = textColor;
    }

    public TextBean(String text, Font font, int x, int y) {
        this.text = text;
        this.font = font;
        this.x = x;
        this.y = y;
    }

    public TextBean(String text, int fontSize, int x, int y) {
        this.text = text;
        this.font = getDefaultFont(fontSize);
        this.x = x;
        this.y = y;
    }

    public void rotate(int rotateDegree){
        this.rotateDegree = rotateDegree;
    }

    private Font getDefaultFont(int fontSize){
        final Set<String> prefers = new HashSet();
        prefers.add("微软雅黑");
        prefers.add("Arial");
        prefers.add("Consolas");
        prefers.add("Symbol");
        prefers.add("Times New Roman");
        prefers.add("sans");

        GraphicsEnvironment ge=GraphicsEnvironment.getLocalGraphicsEnvironment();//取得全部可用的字体
        String[] fnames=ge.getAvailableFontFamilyNames();
        for (int i = 0; i < fnames.length; i++) {
            String fontName = fnames[i];
            if(prefers.contains(fontName)){
                return new Font(fontName, Font.PLAIN, fontSize);
            }
        }
        //Default
        return new Font(Font.MONOSPACED, Font.PLAIN, fontSize);
    }

    protected void drawText(Graphics g, String text, int x, int y) {
        int step = g.getFontMetrics().getHeight() + marginBottom;
        y -= step;
        for (String line : text.split("\n"))
            g.drawString(line, x, y += step);
    }

    protected void doDraw(Context context) throws Exception {

        Graphics2D g=context.canvas.createGraphics();
        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
        g.setColor(textColor);
        g.setFont(font); //字体、字型、字号
        if(rotateDegree % 360 != 0){
            g.rotate(Math.toRadians(rotateDegree), context.canvas.getWidth() / 2, context.canvas.getHeight() / 2);
            g.translate(-(2*x- context.canvas.getWidth()) - font.getSize() * text.length(), -(2*y- context.canvas.getHeight()) + font.getSize());
        }

        drawText(g, text,x, y); //画文字
        g.dispose();

    }
}
